<?php
/**
 * User: 269995848@qq.com
 * Date: 2019/4/1 9:10
 */

namespace app\agent\controller;


use app\lib\enum\FieldsChange;
use app\lib\exception\NoneException;
use app\lib\exception\SuccessMessage;
use app\lib\validate\IDMustBePositiveInt;
use think\db\Where;
use think\facade\Request;

class User extends BaseController{

    public function index(){

        $user=new \app\agent\model\User();

        $data = input('param.');
        $query=http_build_query($data);

        $this->getPageAndSize($data);

        $whereData=new Where();
        if(!empty($data['start_time']) && !empty($data['end_time'])
            && $data['end_time'] > $data['start_time']
        ) {
            $whereData['create_time'] = [
                ['gt', $data['start_time']],
                ['lt', $data['end_time']],
            ];
        }
        if(!empty($data['from'])) {
            $whereData['from'] = intval($data['from']);
        }
        if(!empty($data['qq'])) {
            $whereData['.qq'] = ["like", "%".$data['qq']."%"];
        }


        $recharge=(new \app\agent\model\User)->getRechargeCondition($whereData,$this->from,$this->size);
        $total =\app\agent\model\User::count();

        $pageTotal=ceil($total/$this->size);

        $result=$this->fetch('',[
            'total'=>$total,
            'from'=>FieldsChange::from(),
            'fromValue'=>empty($data['from'])?'':$data['from'],
            'data'=>$recharge,
            'pageTotal'=>$pageTotal,
            'curr'=>$this->page,
            'start_time'=>empty($data['start_time'])?'':$data['start_time'],
            'end_time'=>empty($data['end_time'])?'':$data['end_time'],
            'qq'=>empty($data['qq'])?'':$data['qq'],
            'query'=>$query
        ]);


        return $result;
    }

    public function edit(\think\Request $request){
        (new IDMustBePositiveInt())->goCheck();

        if($request->isPost()){

            $validate=validate('EditUserValidate');
            if(!$validate->check($request->post())){
//                $msg=$validate->getError();
                echoMsg('修改失败，参数错误','/user');
            }

            if(\app\agent\model\User::update($request->post())){
                echoMsg('修改成功','/user');
            }
            echoMsg('修改失败','/user');
        }


        if($user=\app\agent\model\User::get($request->param('id'))){
            return $this->fetch('',['data'=>$user]);
        }
        throw new NoneException();
    }
}